import { defineStore } from 'pinia'

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [],
  }),

  getters: {
    getCart: (state) => state.items,
    getTotal: (state) => {
      return state.items.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
    },
  },

  actions: {
    addToCart(product) {
      const existingItem = this.items.find((item) => item.id === product.id)
      if (existingItem) {
        existingItem.quantity += product.quantity
      } else {
        this.items.push(product)
      }
    },

    removeFromCart(index) {
      this.items.splice(index, 1)
    },

    updateQuantity(index, quantity) {
      if (this.items[index]) {
        this.items[index].quantity = quantity
      }
    },

    clearCart() {
      this.items = []
    },
  },
})
